﻿using BloodApp.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace BloodApp.TCPCommunication
{
    public class TcpService
    {
        public delegate void CustomEventHandler(object sender);
        public event CustomEventHandler ConnectFailure;
        //TCP数据接收线程停止标记
        CancellationTokenSource cancelTokenSource;
        Socket client;
        public Socket Client
        {
            get { return client; }
        }

        public async Task ConnectAsync(string ip = "192.168.2.144", int port = 5555)
        {
            string res = "";
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var connectTask = client.ConnectAsync(ip, port);
                if (await Task.WhenAny(connectTask, Task.Delay(TimeSpan.FromSeconds(2))) == connectTask)
                {
                    cancelTokenSource = new CancellationTokenSource();
                    Task.Factory.StartNew(ReceiveData, cancelTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
                    LogService.Logger.Info($"已成功连接IP：{ip} 设备！");
                }
                else
                    res = "false";
            }
            catch
            {
                res = "false";
            }
            if (ConnectFailure != null && !string.IsNullOrEmpty(res))
            {
                client?.Close();
                ConnectFailure(this);
            }
        }

        public void CloseConnect()
        {
            cancelTokenSource?.Cancel();
            client?.Close();
            client?.Dispose();
            LogService.Logger?.Info($"已断开设备！");
        }

        private void ReceiveData()
        {
            byte[] bytesPro;
            int receiveLength = 0;
            while (!cancelTokenSource.IsCancellationRequested)
            {
                try
                {
                    receiveLength = client.Available;
                    if (receiveLength > 0)
                    {
                        byte[] receiveData = new byte[receiveLength];
                        receiveLength = client.Receive(receiveData, SocketFlags.None);
                        //解析数据
                        for (int i = 0; i < receiveLength; i++)
                            if (ProcessPacketData.ParseNextByte(receiveData[i], out bytesPro))
                            {
                                string strAddr = GetModuleAddrRece(bytesPro[3], bytesPro[4]);

                            }
                    }
                    else
                        Thread.Sleep(500);
                    LogService.Logger.Info("---------------------");
                }
                catch (Exception ex)
                {
                    CloseConnect();
                }
            }
        }


        //获取模块地址
        public string GetModuleAddrRece(byte byte0 = 0x06, byte byte1 = 0x28)
        {
            byte[] bytes = new byte[2];
            var str = Convert.ToString(byte0, 2).PadLeft(8, '0') + Convert.ToString(byte1, 2).PadLeft(8, '0');
            var strZhu = str.Substring(7, 6).PadLeft(8, '0');
            var strZi = str.Substring(13, 3).PadLeft(8, '0');
            var ziID = Convert.ToByte(strZi, 2);
            var zhuID = Convert.ToByte(strZhu, 2);
            return zhuID + "-" + ziID;
        }
    }
}
